<?php

class Ext_Filter_File_UploadToCdn implements Zend_Filter_Interface
{
    /**
     * @var string
     */
    private $_targetDir;

    private $_patternName;

    /**
     * @return string
     */
    public function getTargetDir()
    {
        return $this->_targetDir;
    }

    /**
     * @param string $dir
     * @return Ext_Filter_File_UniqueName
     */
    public function setTargetDir($dir)
    {
        $dir = rtrim($dir, '\/');
        $dir .= DIRECTORY_SEPARATOR;

        $this->_targetDir = $dir;

        return $this;
    }

    /**
     * @param array $options Options to set
     */
    public function __construct($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (is_string($options)) {
            $options = array('targetDir' => $options);
        } elseif (!is_array($options)) {
            require_once 'Zend/Filter/Exception.php';
            throw new Zend_Filter_Exception('Invalid options argument provided to filter');
        }

        if (isset($options['targetDir']) && $options['targetDir']) {
            $this->setTargetDir($options['targetDir']);
        } else {
            require_once 'Zend/Filter/Exception.php';
            throw new Zend_Filter_Exception('Invalid target directory argument provided to filter');
        }

        if (isset($options['patternName']) && $options['patternName']) {
            $this->_patternName = $options['patternName'];
        }
    }

    /**
     * @param string $value full filename
     * @return string
     */
    public function filter($value)
    {
        if ( ! $value) {
            return $value;
        }

        $fileInfo = pathinfo($value);
        $path = Zend_Registry::get('config')->settings->paths->uploads . DIRECTORY_SEPARATOR . $value;
        $newFileName = time() . '.' . $fileInfo['extension'];

        $this->_upload($path, $newFileName);

        return $newFileName;
    }

    protected function _upload($path, $newFileName)
    {
        $file = fopen($path, 'r'); 
        $url = 'ftp://' . Zend_Registry::get('config')->settings->cdn->username . ':'
            . Zend_Registry::get('config')->settings->cdn->password . '@'
            . Zend_Registry::get('config')->settings->cdn->hostname . ':21'
            . '/images/group/' . $newFileName;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_UPLOAD, 1);
        curl_setopt($ch, CURLOPT_INFILE, $file);
        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path));
        $result = curl_exec($ch);
        curl_close($ch);
        fclose($file);
    }
}
